package com.ray.woodencreate.jwt;

import com.alibaba.fastjson.JSON;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.util.SpringApplicationUtil;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.result.MsgCodeConstant;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author bo shen
 * @Description: Jwt操作
 * @Class: Jwt
 * @Package com.toptoday.woodencreate.jwt
 * @date 2018/10/23 15:12
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class Jwt{

    private static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**默认失效时间**/
    private static final  Long default_expire = 60*60*24L;
    /**年**/
    public static final  Long YEAR = 60*60*24*365L;
    /**月**/
    public static final  Long MONTH = 60*60*24*30L;

    /**
     * 创建toaken
     * @param user 用户信息
     * @return
     */
    public static String createToken(LoginUser user, String key){
        String token = null;
        try {
            token = defaultCreateToken(user,key,default_expire);
            defaultSaveRedis(token,key,default_expire);
        }catch (Exception e){
          throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000004);
        }
        return  token;
    }



    /**
     * 创建toaken
     * @param user 用户信息
     * @return
     */
    public static String createToken(LoginUser user, String key,Long expire){
        String token = null;
        try {
            token = defaultCreateToken(user,key,expire);
            defaultSaveRedis(token,key,expire);
        }catch (Exception e){
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000004);
        }
        return  token;
    }



    /**
     * 解析token
     * @param token token
     * @param key 加密串
     * @return
     */
    public static LoginUser parseToken(String token, String key){
        String userString = Jwts.parser().setSigningKey(Base64.getEncoder().encode(key.getBytes())).parseClaimsJws(token).getBody().getSubject();
        log.info("parse info:" + userString);
        LoginUser user =   JSON.parseObject(userString,LoginUser.class);
        user.setToken(token);
        return user;
    }

    /**
     * 创建redis
     * @param token
     * @param key
     * @param expire
     */
    private static void defaultSaveRedis(String token,String key, Long expire) {
        //放入redis
        StringRedisTemplate stringRedisTemplate = SpringApplicationUtil.getBean(StringRedisTemplate.class);
        if(!ObjectUtils.isEmpty(stringRedisTemplate)){
            stringRedisTemplate.opsForValue().set(token, key,expire, TimeUnit.SECONDS);
        }
    }

    /**
     * 创建token
     * @param user
     * @param key
     * @return
     * @throws Exception
     */
    private static String defaultCreateToken(LoginUser user, String key,long time) throws Exception{
        return Jwts.builder()
                .setSubject(user.toString())
                .setExpiration(new Date(System.currentTimeMillis() + time *1000))
                .signWith(SignatureAlgorithm.HS512, Base64.getEncoder().encode(key.getBytes()))
                .compact();
    }

}
